package com.example.volleytest.network;

import android.util.Log;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.example.volleytest.datamodel.Friend;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.Collection;

public class FriendsListRequest extends Request<Collection<Friend>> {
    private final Response.Listener<Collection<Friend>> listener;
    private Gson gson;

    public FriendsListRequest(int method, String url, Response.Listener<Collection<Friend>> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = listener;
        gson = new Gson();
    }

    @Override
    protected Response<Collection<Friend>> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(gson.fromJson(json, ParseResult.class).getFriends(), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(Collection<Friend> response) {
        listener.onResponse(response);
    }

    private static class ParseResult {
        private Collection<Friend> response;

        public Collection<Friend> getFriends() {
            return response;
        }
    }
}
